package com.lw.leetcode.arr.b;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * 398. 随机数索引
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/2 12:38
 */
public class Solution2 {

    private int[] nums;

    public Solution2(int[] nums) {
        this.nums = nums;
    }

    public int pick(int target) {
        Random r = new Random();
        int n = 0;
        int index = 0;
        int[] nums = this.nums;
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            if (nums[i] == target) {
                n++;
                if (r.nextInt(n) == 0) {
                    index = i;
                }
            }
        }
        return index;
    }

}
